﻿using DotNetty.Handlers.Timeout;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using Newtonsoft.Json;
using socketAssist.Handler;
using socketAssist.Procol;
using System;
using System.IO;
using System.Net;
using System.Windows.Forms;

namespace socketAssist
{
    public partial class MainFrm : Form
    {

        private IChannel clientChannel;
        public MainFrm()
        {
            InitializeComponent();
            deviceId_txt.Text = GetGUID();
        }
        private String GetGUID()
        {
            if (!File.Exists("guid.txt"))
            {
                var guid = Guid.NewGuid().ToString();
                File.WriteAllText("guid.txt", guid);
                return guid;
            }
            else
            {
                var guid = File.ReadAllText("guid.txt");
                return guid;
            }
        }

        private async void btn_con_Click(object sender, EventArgs e)
        {
            if (clientChannel == null)
            {
                var group = new MultithreadEventLoopGroup();
                var bootstrap = new Bootstrap();
                bootstrap
                    .Group(group)
                    .Channel<TcpSocketChannel>()
                    .Option(ChannelOption.TcpNodelay, true)
                    .Handler(
                        new ActionChannelInitializer<ISocketChannel>(
                            channel =>
                            {
                                IChannelPipeline pipeline = channel.Pipeline;
                                pipeline.AddLast("framing-enc", new MyProcolEncoder());
                                pipeline.AddLast("framing-dec", new MyProcolDecoder());
                                pipeline.AddLast("idle", new IdleStateHandler(0, 10, 0));
                                var clientHandler = new ClientHandler();
                                clientHandler.OnRecievied += OnRecievedAction;
                                pipeline.AddLast("echo", clientHandler);

                            }));

                clientChannel = await bootstrap.ConnectAsync(txt_address.Text,int.Parse(txt_port.Text));
            }
            else
            {
                IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(txt_address.Text), int.Parse(txt_port.Text));
                await clientChannel.ConnectAsync(endPoint);
            }
        }

        private void btn_send_Click(object sender, EventArgs e)
        {
            if (clientChannel == null)
            {
                MessageBox.Show("连接已关闭");
                return;
            }

            RequestMessage message = new RequestMessage
            {
                body = this.txt_send.Text,
                Cmd = UInt16.Parse(this.txt_cmd.Text)
            };
            clientChannel.WriteAndFlushAsync(message);
        }
        private void OnRecievedAction(String msg)
        {
            if (this.rtx_recieve.InvokeRequired)
            {
                this.rtx_recieve.Invoke(new Action(() =>
                {
                    rtx_recieve.Text += System.Environment.NewLine + msg;
                }));
            }
        }

        private void btn_login_Click(object sender, EventArgs e)
        {
            if (clientChannel == null)
            {
                MessageBox.Show("连接已关闭");
                return;
            }

            RequestMessage message = new RequestMessage
            {
                body = JsonConvert.SerializeObject(new
                {
                    Cmd = 1010,
                    data=new
                    {
                        deviceId=deviceId_txt.Text
                    }
                }),
                Cmd = 1010
            };
            clientChannel.WriteAndFlushAsync(message);
        }

        private void btn_close_Click(object sender, EventArgs e)
        {
            if (clientChannel != null)
            {
                clientChannel.CloseAsync();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            TCPSampler tCPSampler = new TCPSampler();
            tCPSampler.Show();
        }
    }
}
